package com.swn.common.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
 * http请求封装工具类
 * 
 * @author 陶召才
 * @Date 2016年4月14日  下午5:33:27
 * @Note <这里是该类的使用注意事项>
 *
 * TODO
 *

 */
public class HttpClientUtil {  
  
	private static HttpClientUtil instance;
	public HttpClientUtil(){}
	
	public static HttpClientUtil getDefault(){
		synchronized(HttpClientUtil.class){
			if(null == instance){
				instance = new HttpClientUtil();
			}
			return instance;
		}
	}
    /**
     * 通过get方式调用请求地址
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:26:28
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param nameValuePairList：List<NameValuePair>
     * @return
     * @throws Exception
     *
     * @return String
     */
    public static String get(String url, List<NameValuePair> nameValuePairList) throws Exception {  
        String body = null;  
        try {  
        	HttpClient httpClient = new DefaultHttpClient(); 
            // Get请求  
            HttpGet httpget = new HttpGet(url);  
            // 设置参数  
            String str = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList));  
            httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));  
            // 发送请求  
            HttpResponse httpresponse = httpClient.execute(httpget);  
            // 获取返回数据  
            HttpEntity entity = httpresponse.getEntity();  
            body = EntityUtils.toString(entity);  
            if (entity != null) {  
                entity.consumeContent();  
            }  
        }  catch (Exception e) {  
            throw new Exception(e);  
        }  
        return body;  
    } 
    /**
     * 通过post方式调用请求地址
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:27:38
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param nameValuePairList:List<NameValuePair>
     * @return
     *
     * @return String
     */
    public static String post(String url,List<NameValuePair> nameValuePairList){
    	StringBuffer responseStr = new StringBuffer();
		HttpPost httpPost = null;
		HttpEntity he = null; 
		HttpClient hc = null;
		InputStream is  = null;
		BufferedReader br = null;
		try { 
			hc = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			he = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
			httpPost.setEntity(he); 
			HttpResponse ht = hc.execute(httpPost);
			//连接成功
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 	
				HttpEntity het = ht.getEntity();
			    is = het.getContent();
				br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String readLine = null;
				while((readLine =br.readLine()) != null){ 
					responseStr.append(readLine);
				}
			}else{
				responseStr.append("返回失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(is!=null)
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			if(br!=null)
				try {
					br.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
		}
		return responseStr.toString();
	}
      
  
    /**
     * 发送 Post请求 (有待测试)
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:28:34
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param reqXml
     * @return
     * @throws Exception
     *
     * @return String
     */
    public static String post(String url, String reqXml) throws Exception {  
        String body = null;  
        HttpClient httpClient = new DefaultHttpClient(); 
        try {  
            //设置客户端编码  
            httpClient.getParams().setParameter("http.protocol.content-charset",HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);  
            httpClient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,HTTP.UTF_8);  
            // Post请求  
            HttpPost httppost = new HttpPost(url);  
            //设置post编码  
            httppost.getParams().setParameter("http.protocol.content-charset",HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);  
            httppost.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);  
      
            // 设置参数  
             List<NameValuePair> params = new ArrayList<NameValuePair>();  
             params.add(new BasicNameValuePair("$xmldata", reqXml));  
             httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));   
//          StringEntity entity1 = new StringEntity(getUTF8XMLString(reqXml), "UTF-8");  
//          entity1.setContentType("text/xml;charset=UTF-8");  
//          entity1.setContentEncoding("UTF-8");  
//          httppost.setEntity(entity1);  
            //设置报文头  
            httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
            // 发送请求  
            HttpResponse httpresponse = httpClient.execute(httppost);  
            // 获取返回数据  
            HttpEntity entity = httpresponse.getEntity();  
            body = EntityUtils.toString(entity);  
            if (entity != null) {  
                entity.consumeContent();  
            }  
        } catch (Exception e) {  
        	 throw new Exception(e);  
        }  
        return body;  
    }  
      
    /**
     *发送post请求
     * 
     * @author 陶召才
     * @Date 2016年4月14日  下午5:29:27
     * @Note <这里是使用注意事项>
     *
     * @param url
     * @param paramMap：参数
     * @return
     *
     * @return String
     */
	public static String post(String url,Map<String,String> paramMap){
    	StringBuffer responseStr = new StringBuffer();
    	
		HttpPost httpPost = null;
		HttpEntity he = null; 
		HttpClient hc = null;
		InputStream is  = null;
		BufferedReader br = null;
		try { 
			hc = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			//以下几行代码可修改为map2pairs
	    	Iterator<?> it=paramMap.entrySet().iterator();
	    	while(it.hasNext()){//只遍历一次,速度快
	    		Map.Entry e=(Map.Entry)it.next();
	    		NameValuePair nameValuePair = new BasicNameValuePair((String)e.getKey(), (String)e.getValue());
	    		params.add(nameValuePair);
	    	}
	    
			he = new UrlEncodedFormEntity(params, "UTF-8");
			httpPost.setEntity(he); 
			
			HttpResponse ht = hc.execute(httpPost);
			
			//连接成功
			if(ht.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 	
				HttpEntity het = ht.getEntity();
			    is = het.getContent();
				br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String readLine = null;
				while((readLine =br.readLine()) != null){ 
					responseStr.append(readLine);
				}
			}else{
				responseStr.append("返回失败！");
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(is!=null)
				try {
					is.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			if(br!=null)
				try {
					br.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
		}
		return changeCoding(responseStr.toString());
	}
	
	private static String changeCoding(String s){
	    StringBuffer sb = new StringBuffer();
	    Pattern p = Pattern.compile("(?i)\\\\u([\\da-f]{4})");
        Matcher m = p.matcher(s);
        while(m.find()) {
            m.appendReplacement(sb, Character.toString((char)Integer.parseInt(m.group(1), 16)));
        }
        m.appendTail(sb);
        return sb.toString();
}
	



	/**
	 * map转换为namevaluepair的列表
	 * @param message
	 * @return
	 */
	private List<NameValuePair> map2pairs(Map<String, String> message){
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		if(null != message){
			for(Map.Entry<String, String> entry : message.entrySet()){
				pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		return pairs;
	}
	 public static String get(String url) throws Exception {  
	        String body = null;  
	        try {  
	        	HttpClient httpClient = new DefaultHttpClient(); 
	            // Get请求  
	            HttpGet httpget = new HttpGet(url);  
	            httpget.setURI(new URI(httpget.getURI().toString() ));  
	            // 发送请求  
	            HttpResponse httpresponse = httpClient.execute(httpget);  
	            // 获取返回数据  
	            HttpEntity entity = httpresponse.getEntity();  
	            body = EntityUtils.toString(entity);  
	            if (entity != null) {  
	                entity.consumeContent();  
	            }  
	        }  catch (Exception e) {  
	            throw new Exception(e);  
	        }  
	        return body;  
	    } 
	//验证登录密码是否正确
    public static boolean verification(String phone,String code){
    	boolean tag=false;
    	try {
    	      //微信密码  验证	
  		     
	   	      String url="https://msg.baiduor.com/api/code/verify?mobile="+phone+"&code="+code;
	   	      JSONObject object = JSON.parseObject(sendHttpsRequestBySsl(url,null,2)); 
			  String status=object.getString("verified");
			  if(StringUtil.isNotEmpty(status)&& status.equals("true")){ 
				tag=true;
			  }else{
				 //短信密码 验证
		   	      Map<String,String> mm=new HashMap<String,String>();
		   	      mm.put("mobilephone",phone);
		   	      mm.put("password",Md5Util.getMd5(code));
		   	      mm.put("token","KLiew_4GFGUY_glffuy");
		   	      url="http://www.baiduor.com/api.php?a=auth_dynamic_password";
				  object = JSON.parseObject(sendHttpsRequestBySsl(url,mm,1)); 
				  status=object.getString("status");
				  if(StringUtil.isNotEmpty(status)&& status.equals("0")){ 
					tag=true;
				  }
			  }
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return tag;
    }
  
    /**
     *  发送HTTPS	POST/GET请求
     * @param url          要访问的HTTPS地址,
     * @param params        POST访问的参数Map对象
     * @param type          1:POST  2:GET
     * @return
     */
	public static  String sendHttpsRequestBySsl(String url, Map<String, String> params,int type) {
		String responseContent = null;
		HttpClient httpClient = new DefaultHttpClient();
		//创建TrustManager
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		//这个好像是HOST验证
		X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
			public boolean verify(String arg0, SSLSession arg1) {
				return true;
			}
			public void verify(String arg0, SSLSocket arg1) throws IOException {}
			public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {}
			public void verify(String arg0, X509Certificate arg1) throws SSLException {}
		};
		try {
			//TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
			SSLContext ctx = SSLContext.getInstance("TLS");
			//使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
			ctx.init(null, new TrustManager[] { xtm }, null);
			//创建SSLSocketFactory
			SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
			socketFactory.setHostnameVerifier(hostnameVerifier);
			//通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
			httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
			HttpPost httpPost =null;
			HttpGet httpget=null;
			HttpResponse response = null;
			if(type==1){ //post请求
				httpPost = new HttpPost(url);
				List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
				for (Map.Entry<String, String> entry : params.entrySet()) {
					formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
				response=httpClient.execute(httpPost);
			}else{ // Get请求  
				httpget= new HttpGet(url);  
	            httpget.setURI(new URI(httpget.getURI().toString() ));  
	            response=httpClient.execute(httpget);
			}
			HttpEntity entity = response.getEntity(); // 获取响应实体
			if (entity != null) {
				responseContent = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			httpClient.getConnectionManager().shutdown();
		}
		return responseContent;
	}
  
    public static void main(String[] args) {
    		
//    		StringBuffer xmlStr = new StringBuffer();
//    		xmlStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
//    		.append("\n");
//    		xmlStr.append("<Params>").append("\n");
//    		xmlStr.append("  <InterfaceMode>IConsultationReg</InterfaceMode>")
//    				.append("\n");
//    		xmlStr.append("  <FuncCode>A100010</FuncCode>").append("\n");
//    		xmlStr.append("  <DataList>").append("\n");
//    		xmlStr.append("     <Name>张三</Name>").append("\n");
//    		xmlStr.append("     <ID>777</ID>").append("\n");
//    		xmlStr.append("    <Age>30</Age>").append("\n");
//    		xmlStr.append("  </DataList>").append("\n");
//    		xmlStr.append("</Params>").append("\n");
//    		
//    		
//        	Map m = new HashMap();
//        	m.put("xml", xmlStr.toString());
//        	String ss = post("http://localhost:8080/successMainFrame/service.action",m);
//        	System.out.println(ss);
    	 String url="http://www.baiduor.com/api.php?a=auth_dynamic_password";
		 String phone="15098960112";
		 String code="761882";
//		 15098960112  761882
		  List<NameValuePair> parms = new ArrayList<NameValuePair>();
	      parms.add(new BasicNameValuePair("mobilephone",phone));
	      parms.add(new BasicNameValuePair("password",Md5Util.getMd5(code)));
	      parms.add(new BasicNameValuePair("token","KLiew_4GFGUY_glffuy"));
//	      Map<String,String> mm=new HashMap<String,String>();
//	      mm.put("mobilephone", phone);
//	      mm.put("password", Md5Util.getMd5(code));
//	      mm.put("token", "KLiew_4GFGUY_glffuy");
    	  String a=post(url,parms);
    	  System.out.println(a);
    	}

    /**
	 * 
	 * 功能： post json参数
	 * 
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param: @param jsonParam
	 * @param: @param urls
	 * @param: @return
	 * @return: String
	 * @author : 孙荆阁
	 * @Date 2018年6月30日 下午5:08:55 修改日期 修改人 修改内容 <多次修改需另起一行>
	 */
	public static String getJsonData(net.sf.json.JSONObject jsonParam, String urls) {
		StringBuffer sb = new StringBuffer();
		try {
			// 创建url资源
			URL url = new URL(urls);
			// 建立http连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置允许输出
			conn.setDoOutput(true);
			// 设置允许输入
			conn.setDoInput(true);
			// 设置不用缓存
			conn.setUseCaches(false);
			// 设置传递方式
			conn.setRequestMethod("POST");
			// 设置维持长连接
			conn.setRequestProperty("Connection", "Keep-Alive");
			// 设置文件字符集:
			conn.setRequestProperty("Charset", "UTF-8");
			// 转换为字节数组
			byte[] data = (jsonParam.toString()).getBytes();
			// 设置文件长度
			conn.setRequestProperty("Content-Length",
					String.valueOf(data.length));
			// 设置文件类型:
			conn.setRequestProperty("contentType", "application/json");
			// 开始连接请求
			conn.connect();
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// 写入请求的字符串
			out.write((jsonParam.toString()).getBytes());
			out.flush();
			out.close();

			// 请求返回的状态
			if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
				// 请求返回的数据
				InputStream in1 = conn.getInputStream();
				try {
					String readLine = new String();
					BufferedReader responseReader = new BufferedReader(
							new InputStreamReader(in1, "UTF-8"));
					while ((readLine = responseReader.readLine()) != null) {
						sb.append(readLine).append("\n");
					}
					responseReader.close();

				} catch (Exception e1) {
					e1.printStackTrace();
				}
			} else {
			}

		} catch (Exception e) {

		}

		return sb.toString();

	}
    
}
